<?php
class myMongo {
	private $mongo;
	private $db;
	private $collection;
	function __construct($host, $user, $password) {
		try {
			$this->mongo = new Mongo ( "mongodb://" . $user . ":" . $password . "@" . $host );
		} catch ( exception $e ) {
			echo $e->getMessage ();
			exit ();
		}
	}
	public function selectDB($dbname) {
		$this->db = $this->mongo->selectDB ( $dbname );
	}
	public function selectCollection($collection) {
		$this->collection = $this->db->selectCollection ( $collection );
	}
	/**
	 * 
	 * 
	 * @param array $data
	 * @param unknown_type $collection
	 * @param array $option safe,fsync,timeout
	 * @throws Exception
	 */
	public function insert(Array $data, Array $option = array()) {
		if (empty ( $data )) {
			throw new Exception ( "insert emtpy data" );
			exit();
		}
		try {
			$return = $this->collection->insert ( $data, $option );
		} catch ( Exception $e ) {
			echo $e->getMessage ();
			exit ();
		}
		return true;
	}
	/**
	 * 
	 * 
	 * @param array $where
	 * @param array $option justOne,safe,fsync,timeout
	 * @throws Exception
	 */
	public function delete(Array $where, Array $option = array()) {
		try {
			$return = $this->collection->remove ( $where, $option );
		} catch ( Exception $e ) {
			echo $e->getMessage ();
			exit ();
		}
	}
	/**
	 * 
	 * @param array $field
	 * @param array $where
	 */
	public function findAll(Array $field = array(), Array $where = array()) {
		try {
			$cursor = $this->collection->find ( $where, $field );
			$array = iterator_to_array ( $cursor );
		} catch ( Exception $e ) {
			echo $e->getMessage ();
			exit ();
		}
		return $array;
	}
	/**
	 * 
	 * Enter description here ...
	 * @param array $data
	 * @param array $where
	 * @param array $option upsert,multiple,safe,fsync,timeout
	 * @throws Exception
	 */
	public function update(Array $data, Array $where, Array $option = array()) {
		if (empty($data)) {
			throw new Exception("update date is empty");
			exit;
		}
		try {
			$result = $this->collection->update ( $where, $data, $option);
		} catch ( Exception $e ) {
			echo $e->getMessage ();
			exit ();
		}
		return $result;
	}
}

//$mongo = new myMongo('192.168.128.128', 'firoyang', 'firoyang');
//$mongo->selectDB('test');
//$mongo->selectCollection('cc');
//$mongo->insert(array('name'=> 'firoyang','age'=> '1228'));
//$mongo->insert(array('name'=> 'firoyang','age'=> '1228', 'to' => 'delete'));
//$mongo->update(array('$set' => array('say'=> 'hehe')), array('name'=> 'firoyang'), array("multiple" => true));
//$mongo->delete(array('to' => 'delete'));
////$mongo->delete(array());
//echo "<pre>";
//var_dump($mongo->findAll());
//echo "</pre>";

